<?php


namespace App\Services;

use App\Models\Comment;
use App\Models\User;

class CommentService
{
    public function commentList($novelId, $page)
    {
        $comments = Comment::query()->where('novel_id', $novelId)
            ->skip(($page - 1) * 50)
            ->limit(50)
            ->get();

        $userIds = $comments->pluck('user_id');

        $users = User::query()->whereIn('id', $userIds)->get()->toArray();

        $usersMap = array_column($users, null, 'id');

        $comments->each(function (&$comment) use ($usersMap) {
            $userId = $comment->user_id;
            $comment['user_name'] = $usersMap[$userId]['user_name'] ?? '';
            $comment['headpic'] = $usersMap[$userId]['headpic'] ?? '';
        });

        return toCamelCaseKey($comments->toArray());
    }

    public function createComment($novelId, $userId, $comment)
    {
        $comment = Comment::query()->create([
            'novel_id' => $novelId,
            'user_id' => $userId,
            'content' => $comment,
        ]);
        return $comment;
    }
}
